const fs = require("fs");
const path = require("path");
const url = require("url");
//私有方法,当前模块内部有用
//let getFileMine = function (extname) {}===function getFileMine(extname) {}
let getFileMine = function (extname) {
  let data = fs.readFileSync("./utils/mime.json");
  let mimeObj = JSON.parse(data.toString());
  return mimeObj[extname];
};
exports.static = function (req, res, staticPath) {
  let pathname = url.parse(req.url).pathname;
  pathname = pathname == "/" ? "/index.html" : pathname;
  let extname = path.extname(pathname);
  if (pathname !== "/favicon.ico") {
    fs.readFile("./" + staticPath + pathname, (err, data) => {
      if (err) {
        console.log("404");
        res.writeHead(404, { "Content-Type": "text/html;charset=utf-8" });
        res.end("这个页面不存在");
        return;
      }
      let mime = getFileMine(extname);
      res.writeHead(200, { "Content-Type": `${mime};charset=utf-8` });
      res.end(data);
    });
  }
};
